
import Speech from 'speak-tts'
import {ref} from'vue'
  
//https://www.npmjs.com/package/speak-tts
  // 语音合成实例
  // 定义响应式变量
const text = ref('Hello, how are you today?');
const voices = ref([]);
const selectedVoice = ref('');
const supportMessage = ref('');
  let speechInstance;

  // 初始化语音
  export  const initSpeech = () => {
    const speech = new Speech();
    speech.init({
      volume: 0.5, // 音量
      lang: 'en-GB', // 默认语言
      rate: 1, // 语速
      pitch: 1, // 音调
    }).then((data) => {
      // console.log('语音合成准备就绪', data);
      voices.value = data.voices;
      supportMessage.value = speech.hasBrowserSupport()
        ? '太好了，你的浏览器支持语音合成'
        : '抱歉，你的浏览器不支持语音合成。请尝试使用Chrome或Safari！';
    }).catch(e => {
      console.error('初始化时发生错误:', e);
    });
  
    speechInstance = speech;
  }

  // 播放语音
  export  const playSpeech = (text) => {
    // const voiceName = document.querySelector('select').selectedOptions[0].dataset.name;
    const a="zh-CN"
    const b="Microsoft Xiaoxiao Online (Natural) - Chinese (Mainland)"
    const c='en-GB'
    // if (selectedVoice.value) speechInstance.setLanguage(selectedVoice.value);
    // if (voiceName) speechInstance.setVoice(voiceName);
  

    // 定义一个匹配表情符号的正则表达式
  const emojiRegex = /[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu;

    
    if (a) speechInstance.setLanguage(a);
    if (b) speechInstance.setVoice(b);
    speechInstance.speak({
      text: text.replace(emojiRegex, ''),
      queue: false, // 是否排队等待播放
    }).catch(e => {
      console.error('发生错误:', e);
    });
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////
  